<template>
  <div class="calendar-page">
    <!-- 月份切换器 -->
    <div class="month-switcher">
      <van-icon name="arrow-left" @click="store.prevMonth(); loadHolidayData()" class="nav-arrow" />
      <div class="month-display" @click="showMonthPicker = true">
        <span class="year">{{ store.currentYear }}年</span>
        <span class="month">{{ store.currentMonth }}月</span>
        <van-icon name="arrow-down" size="12" />
      </div>
      <van-icon name="arrow" @click="store.nextMonth(); loadHolidayData()" class="nav-arrow" />
      <van-button 
        size="small" 
        plain 
        round 
        @click="goToday"
        class="today-btn"
      >
        今天
      </van-button>
    </div>
    
    <!-- 图例说明 -->
    <div class="legend">
      <div class="legend-item">
        <span class="dot workday"></span>
        <span>工作日</span>
      </div>
      <div class="legend-item">
        <span class="dot weekend"></span>
        <span>周末</span>
      </div>
      <div class="legend-item">
        <span class="dot holiday"></span>
        <span>节假日</span>
      </div>
      <div class="legend-item">
        <span class="dot makeup"></span>
        <span>调休补班</span>
      </div>
      <div class="legend-item">
        <span class="dot rest"></span>
        <span>休息</span>
      </div>
    </div>
    
    <!-- 日历主体 - 支持滑动 -->
    <div 
      class="calendar-wrapper"
      @touchstart="handleTouchStart"
      @touchmove="handleTouchMove"
      @touchend="handleTouchEnd"
    >
      <!-- 星期标题 -->
      <div class="weekday-header">
        <div 
          v-for="(day, index) in weekdays" 
          :key="day"
          class="weekday-cell"
          :class="{ 'weekend': index >= 5 }"
        >
          {{ day }}
        </div>
      </div>
      
      <!-- 日期网格 -->
      <div class="calendar-grid">
        <div 
          v-for="(day, index) in store.currentMonthDays"
          :key="day.date || `empty-${index}`"
          :class="getDayClasses(day)"
          @click="handleDayClick(day)"
        >
          <template v-if="!day.isEmpty">
            <!-- 日期数字 -->
            <div class="day-number">{{ day.day }}</div>
            
            <!-- 日期类型指示器 -->
            <div class="day-indicator" :class="getIndicatorClass(day)"></div>
            
            <!-- 节假日名称 -->
            <div v-if="day.holidayName" class="holiday-name" :class="{ 'makeup-day': day.dateType === 3 }">
              {{ getHolidayDisplayText(day) }}
            </div>
            
            <!-- 用户状态标记 -->
            <div v-if="day.userStatus" class="status-badge" :class="day.userStatus">
              {{ getStatusIcon(day.userStatus) }}
            </div>
            
            <!-- 今天标记 -->
            <div v-if="day.isToday" class="today-ring"></div>
          </template>
        </div>
      </div>
    </div>
    
    <!-- 出差提示 -->
    <div v-if="!store.user.tripStartDate" class="trip-notice">
      <van-icon name="warning-o" />
      <span>请先设置出差开始日期，点击日历中的日期即可设置</span>
    </div>
    
    <!-- 当前休息状态 -->
    <div v-if="store.hasOngoingRest" class="ongoing-rest-card">
      <div class="card-header">
        <van-icon name="clock-o" />
        <span>正在休息中</span>
      </div>
      <div class="card-content">
        <div class="rest-info">
          <span class="label">开始日期</span>
          <span class="value">{{ store.ongoingRest.startDate }}</span>
        </div>
        <div class="rest-info">
          <span class="label">已休息</span>
          <span class="value">{{ getRestDays(store.ongoingRest.startDate) }} 天</span>
        </div>
      </div>
    </div>
    
    <!-- 日期操作弹窗 -->
    <van-action-sheet
      v-model:show="showDayActions"
      :title="selectedDay?.date"
      :description="getDayDescription()"
      :actions="dayActions"
      cancel-text="取消"
      @select="handleActionSelect"
      class="day-action-sheet"
    />
    
    <!-- 设置出差日期确认 -->
    <van-dialog
      v-model:show="showTripConfirm"
      title="设置出差开始日期"
      show-cancel-button
      @confirm="confirmSetTripDate"
    >
      <div class="dialog-content">
        <p>确定将 <strong>{{ selectedDay?.date }}</strong> 设为出差开始日期吗？</p>
      </div>
    </van-dialog>
    
    <!-- 月份选择器 -->
    <van-popup
      v-model:show="showMonthPicker"
      position="bottom"
      round
      class="month-picker-popup"
    >
      <van-date-picker
        v-model="monthPickerValue"
        title="选择月份"
        :columns-type="['year', 'month']"
        :min-date="new Date(2020, 0)"
        :max-date="new Date(2030, 11)"
        @confirm="handleMonthConfirm"
        @cancel="showMonthPicker = false"
      />
    </van-popup>
    
    <!-- 休息记录编辑弹窗 -->
    <van-popup
      v-model:show="showRestEdit"
      position="bottom"
      round
      closeable
      class="rest-edit-popup"
    >
      <div class="rest-edit-content">
        <h3>{{ editingRecord ? '编辑休息记录' : '添加休息记录' }}</h3>
        
        <van-cell-group inset class="edit-form">
          <van-cell 
            title="开始日期" 
            :value="restForm.startDate || '请选择'"
            is-link
            @click="openDatePicker('start')"
          />
          <van-cell 
            title="结束日期" 
            :value="restForm.endDate || '进行中'"
            is-link
            @click="openDatePicker('end')"
          />
          <van-field
            v-model="restForm.description"
            label="描述"
            placeholder="可选，添加备注"
            maxlength="200"
          />
        </van-cell-group>
        
        <div class="edit-actions">
          <van-button block round type="primary" @click="saveRestRecord" :loading="saving">
            保存
          </van-button>
        </div>
      </div>
    </van-popup>
    
    <!-- 日期选择器 -->
    <van-popup
      v-model:show="showDatePicker"
      position="bottom"
      round
      class="date-picker-popup"
    >
      <van-date-picker
        v-model="datePickerValue"
        :title="datePickerTitle"
        :min-date="datePickerMinDate"
        :max-date="datePickerMaxDate"
        @confirm="handleDatePickerConfirm"
        @cancel="showDatePicker = false"
      />
    </van-popup>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { showToast, showConfirmDialog } from 'vant'
import { useAppStore } from '../stores/index.js'

const store = useAppStore()

const weekdays = ['一', '二', '三', '四', '五', '六', '日']

// 弹窗状态
const showDayActions = ref(false)
const showTripConfirm = ref(false)
const showMonthPicker = ref(false)
const showRestEdit = ref(false)
const showDatePicker = ref(false)

// 选中的日期
const selectedDay = ref(null)
const dayActions = ref([])

// 月份选择器
const monthPickerValue = ref([
  store.currentYear.toString(),
  store.currentMonth.toString().padStart(2, '0')
])

// 休息记录编辑
const editingRecord = ref(null)
const restForm = ref({
  startDate: '',
  endDate: '',
  description: ''
})
const saving = ref(false)

// 日期选择器
const datePickerType = ref('start')
const datePickerValue = ref([])
const datePickerTitle = computed(() => 
  datePickerType.value === 'start' ? '选择开始日期' : '选择结束日期'
)
const datePickerMinDate = computed(() => {
  if (datePickerType.value === 'end' && restForm.value.startDate) {
    return new Date(restForm.value.startDate)
  }
  return new Date(2020, 0, 1)
})
const datePickerMaxDate = computed(() => new Date())

// 滑动相关
const touchStartX = ref(0)
const touchStartY = ref(0)
const isSwiping = ref(false)

// 处理触摸开始
const handleTouchStart = (e) => {
  touchStartX.value = e.touches[0].clientX
  touchStartY.value = e.touches[0].clientY
  isSwiping.value = true
}

// 处理触摸移动
const handleTouchMove = (e) => {
  if (!isSwiping.value) return
  
  const deltaX = e.touches[0].clientX - touchStartX.value
  const deltaY = e.touches[0].clientY - touchStartY.value
  
  // 如果垂直滑动距离大于水平滑动距离，不处理
  if (Math.abs(deltaY) > Math.abs(deltaX)) {
    isSwiping.value = false
  }
}

// 处理触摸结束
const handleTouchEnd = (e) => {
  if (!isSwiping.value) return
  isSwiping.value = false
  
  const touchEndX = e.changedTouches[0].clientX
  const deltaX = touchEndX - touchStartX.value
  const threshold = 50 // 滑动阈值
  
  if (Math.abs(deltaX) > threshold) {
    if (deltaX > 0) {
      // 向右滑动，显示上个月
      store.prevMonth()
      loadHolidayData()
    } else {
      // 向左滑动，显示下个月
      store.nextMonth()
      loadHolidayData()
    }
  }
}

// 获取节假日显示文字（区分节假日和调休补班）
const getHolidayDisplayText = (day) => {
  if (!day.holidayName) return ''
  
  // 如果是调休补班（dateType === 3），显示"补班"
  if (day.dateType === 3) {
    return '补班'
  }
  
  // 如果是节假日（dateType === 2），显示节日名称的前两个字
  const name = day.holidayName
  if (name.length > 2) {
    return name.substring(0, 2)
  }
  return name
}

// 获取日期样式类
const getDayClasses = (day) => {
  if (day.isEmpty) {
    return ['calendar-day', 'empty']
  }
  
  return [
    'calendar-day',
    `type-${day.dateType}`,
    {
      'before-trip': day.isBeforeTrip && store.user.tripStartDate,
      'is-today': day.isToday,
      'has-status': day.userStatus,
      'trip-start': day.userStatus === 'trip_start',
      'rest-day': day.userStatus?.includes('rest')
    }
  ]
}

// 获取指示器样式类
const getIndicatorClass = (day) => {
  if (day.userStatus?.includes('rest')) return 'rest'
  if (day.userStatus === 'trip_start') return 'trip'
  if (day.dateType === 2) return 'holiday'
  if (day.dateType === 1) return 'weekend'
  if (day.dateType === 3) return 'makeup'
  return 'workday'
}

// 获取状态图标
const getStatusIcon = (status) => {
  const icons = {
    'trip_start': '🚀',
    'rest_start': '🏖️',
    'rest_end': '✅',
    'rest_period': '😴'
  }
  return icons[status] || ''
}

// 获取日期描述
const getDayDescription = () => {
  if (!selectedDay.value) return ''
  const parts = [selectedDay.value.weekdayName, selectedDay.value.dateTypeName]
  if (selectedDay.value.holidayName) {
    parts.push(selectedDay.value.holidayName)
  }
  return parts.join(' · ')
}

// 处理日期点击
const handleDayClick = (day) => {
  if (day.isEmpty) return
  
  selectedDay.value = day
  
  // 如果没有设置出差开始日期
  if (!store.user.tripStartDate) {
    showTripConfirm.value = true
    return
  }
  
  // 如果点击的是出差开始之前的日期
  if (day.isBeforeTrip) {
    showTripConfirm.value = true
    return
  }
  
  // 分析可用操作
  const options = store.analyzeClickOptions(day.date)
  
  if (options.length === 0) {
    showToast('此日期暂无可用操作')
    return
  }
  
  // 构建操作列表
  dayActions.value = options.map(opt => ({
    name: opt.label,
    subname: opt.description,
    value: opt,
    color: opt.priority === 'high' ? '#6366f1' : '#64748b'
  }))
  
  showDayActions.value = true
}

// 确认设置出差日期
const confirmSetTripDate = async () => {
  try {
    await store.setTripStartDate(selectedDay.value.date)
    showToast({
      message: '设置成功',
      icon: 'success'
    })
    
    // 刷新统计
    await store.getStatistics({ includeTravel: store.includeTravel })
  } catch (error) {
    showToast({
      message: error.message || '设置失败',
      icon: 'fail'
    })
  }
}

// 处理操作选择
const handleActionSelect = async (action) => {
  showDayActions.value = false
  const option = action.value
  
  try {
    switch (option.type) {
      case 'new_rest_start':
        restForm.value = {
          startDate: option.startDate,
          endDate: '',
          description: ''
        }
        editingRecord.value = null
        showRestEdit.value = true
        break
        
      case 'new_rest_end':
        restForm.value = {
          startDate: '',
          endDate: option.endDate,
          description: ''
        }
        editingRecord.value = null
        showRestEdit.value = true
        break
        
      case 'end_current_rest':
        await showConfirmDialog({
          title: '结束休息',
          message: option.description
        })
        await store.updateRestRecord(option.target.id, {
          ...option.target,
          endDate: option.newDate
        })
        showToast({ message: '休息已结束', icon: 'success' })
        await store.getStatistics({ includeTravel: store.includeTravel })
        break
        
      case 'modify_start':
        await showConfirmDialog({
          title: '修改开始日期',
          message: option.description
        })
        await store.updateRestRecord(option.target.id, {
          ...option.target,
          startDate: option.newDate
        })
        showToast({ message: '修改成功', icon: 'success' })
        await store.getStatistics({ includeTravel: store.includeTravel })
        break
        
      case 'modify_end':
        await showConfirmDialog({
          title: '修改结束日期',
          message: option.description
        })
        await store.updateRestRecord(option.target.id, {
          ...option.target,
          endDate: option.newDate
        })
        showToast({ message: '修改成功', icon: 'success' })
        await store.getStatistics({ includeTravel: store.includeTravel })
        break
    }
  } catch (error) {
    if (error !== 'cancel' && error.message !== 'cancel') {
      showToast({
        message: error.message || '操作失败',
        icon: 'fail'
      })
    }
  }
}

// 打开日期选择器
const openDatePicker = (type) => {
  datePickerType.value = type
  const currentDate = type === 'start' ? restForm.value.startDate : restForm.value.endDate
  
  if (currentDate) {
    datePickerValue.value = currentDate.split('-')
  } else {
    const today = new Date()
    datePickerValue.value = [
      today.getFullYear().toString(),
      (today.getMonth() + 1).toString().padStart(2, '0'),
      today.getDate().toString().padStart(2, '0')
    ]
  }
  
  showDatePicker.value = true
}

// 处理日期选择确认
const handleDatePickerConfirm = ({ selectedValues }) => {
  const dateStr = selectedValues.join('-')
  
  if (datePickerType.value === 'start') {
    restForm.value.startDate = dateStr
  } else {
    restForm.value.endDate = dateStr
  }
  
  showDatePicker.value = false
}

// 保存休息记录
const saveRestRecord = async () => {
  if (!restForm.value.startDate) {
    showToast('请选择开始日期')
    return
  }
  
  saving.value = true
  
  try {
    const record = {
      startDate: restForm.value.startDate,
      endDate: restForm.value.endDate || null,
      description: restForm.value.description || ''
    }
    
    if (editingRecord.value) {
      await store.updateRestRecord(editingRecord.value.id, record)
      showToast({ message: '更新成功', icon: 'success' })
    } else {
      await store.addRestRecord(record)
      showToast({ message: '添加成功', icon: 'success' })
    }
    
    showRestEdit.value = false
    await store.getStatistics({ includeTravel: store.includeTravel })
  } catch (error) {
    showToast({
      message: error.message || '保存失败',
      icon: 'fail'
    })
  } finally {
    saving.value = false
  }
}

// 月份选择确认
const handleMonthConfirm = ({ selectedValues }) => {
  store.currentYear = parseInt(selectedValues[0])
  store.currentMonth = parseInt(selectedValues[1])
  showMonthPicker.value = false
  loadHolidayData()
}

// 回到今天
const goToday = () => {
  store.goToday()
  loadHolidayData()
}

// 加载节假日数据
const loadHolidayData = async () => {
  try {
    const result = await store.getHolidayData(store.currentYear)
    // 如果该年份暂无节假日数据，显示提示
    if (result && result.hasData === false) {
      showToast({
        message: `${result.emptyYear || store.currentYear}年暂无节假日数据`,
        icon: 'info-o',
        duration: 2000
      })
    }
  } catch (error) {
    console.error('加载节假日数据失败:', error)
  }
}

// 计算休息天数
const getRestDays = (startDate) => {
  const start = new Date(startDate)
  const today = new Date()
  const diffTime = today - start
  const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
  return Math.max(1, diffDays)
}

onMounted(() => {
  loadHolidayData()
})
</script>

<style scoped>
.calendar-page {
  padding: 16px;
  padding-bottom: 80px;
}

/* 月份切换器 */
.month-switcher {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 16px;
  margin-bottom: 16px;
  padding: 12px;
  background: var(--card-bg);
  border-radius: 12px;
}

.nav-arrow {
  font-size: 20px;
  color: var(--text-secondary);
  padding: 8px;
  cursor: pointer;
  transition: color 0.2s;
}

.nav-arrow:active {
  color: var(--accent-primary);
}

.month-display {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background: var(--card-bg-hover);
  border-radius: 8px;
  cursor: pointer;
}

.month-display .year {
  font-size: 14px;
  color: var(--text-secondary);
}

.month-display .month {
  font-size: 18px;
  font-weight: 600;
  color: var(--text-primary);
}

.today-btn {
  background: transparent !important;
  border-color: var(--accent-primary) !important;
  color: var(--accent-primary) !important;
  font-size: 12px;
  padding: 0 12px;
  height: 28px;
}

/* 图例 */
.legend {
  display: flex;
  justify-content: center;
  gap: 16px;
  margin-bottom: 12px;
  flex-wrap: wrap;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 4px;
  font-size: 11px;
  color: var(--text-muted);
}

.dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.dot.workday { background: var(--accent-primary); }
.dot.weekend { background: var(--warning-color); }
.dot.holiday { background: var(--danger-color); }
.dot.makeup { background: var(--success-color); }
.dot.rest { background: var(--accent-secondary); }

/* 日历主体 */
.calendar-wrapper {
  background: var(--card-bg);
  border-radius: 16px;
  overflow: hidden;
}

/* 星期标题 */
.weekday-header {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  background: var(--card-bg-hover);
}

.weekday-cell {
  padding: 12px 0;
  text-align: center;
  font-size: 13px;
  font-weight: 500;
  color: var(--text-secondary);
}

.weekday-cell.weekend {
  color: var(--warning-color);
}

/* 日期网格 */
.calendar-grid {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 2px;
  padding: 8px;
}

.calendar-day {
  aspect-ratio: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  position: relative;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.2s;
  min-height: 48px;
}

.calendar-day:not(.empty):active {
  transform: scale(0.95);
  background: var(--card-bg-hover);
}

.calendar-day.empty {
  cursor: default;
}

.calendar-day.before-trip {
  opacity: 0.4;
}

/* 今天标记 */
.calendar-day.is-today {
  background: rgba(99, 102, 241, 0.1);
}

.today-ring {
  position: absolute;
  inset: 2px;
  border: 2px solid var(--accent-primary);
  border-radius: 8px;
  pointer-events: none;
}

/* 日期数字 */
.day-number {
  font-size: 15px;
  font-weight: 500;
  color: var(--text-primary);
  line-height: 1;
}

/* 日期类型指示器 */
.day-indicator {
  width: 4px;
  height: 4px;
  border-radius: 50%;
  margin-top: 4px;
}

.day-indicator.workday { background: var(--accent-primary); opacity: 0.5; }
.day-indicator.weekend { background: var(--warning-color); }
.day-indicator.holiday { background: var(--danger-color); }
.day-indicator.makeup { background: var(--success-color); }
.day-indicator.rest { background: var(--accent-secondary); }
.day-indicator.trip { background: var(--success-color); }

/* 节假日名称 */
.holiday-name {
  font-size: 9px;
  color: var(--danger-color);
  margin-top: 2px;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 调休补班日名称 */
.holiday-name.makeup-day {
  color: var(--success-color);
}

/* 状态标记 */
.status-badge {
  position: absolute;
  top: 2px;
  right: 2px;
  font-size: 10px;
  line-height: 1;
}

/* 休息日背景 */
.calendar-day.rest-day {
  background: var(--rest-bg);
}

.calendar-day.trip-start {
  background: var(--trip-start-bg);
}

/* 出差提示 */
.trip-notice {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 12px 16px;
  margin-top: 16px;
  background: rgba(245, 158, 11, 0.15);
  border-radius: 12px;
  color: var(--warning-color);
  font-size: 13px;
}

/* 正在休息卡片 */
.ongoing-rest-card {
  margin-top: 16px;
  padding: 16px;
  background: var(--card-bg);
  border-radius: 12px;
  border: 1px solid var(--accent-secondary);
}

.ongoing-rest-card .card-header {
  display: flex;
  align-items: center;
  gap: 8px;
  color: var(--accent-secondary);
  font-weight: 600;
  margin-bottom: 12px;
}

.ongoing-rest-card .card-content {
  display: flex;
  gap: 24px;
}

.rest-info {
  display: flex;
  flex-direction: column;
  gap: 4px;
}

.rest-info .label {
  font-size: 12px;
  color: var(--text-muted);
}

.rest-info .value {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

/* 日期操作弹窗 */
.day-action-sheet :deep(.van-action-sheet__header) {
  color: var(--text-primary);
}

.day-action-sheet :deep(.van-action-sheet__description) {
  color: var(--text-secondary);
}

/* 月份选择器弹窗 */
.month-picker-popup {
  background: var(--card-bg) !important;
}

.month-picker-popup :deep(.van-picker) {
  background: var(--card-bg) !important;
}

.month-picker-popup :deep(.van-picker__toolbar) {
  background: var(--card-bg);
}

.month-picker-popup :deep(.van-picker__title) {
  color: var(--text-primary);
}

.month-picker-popup :deep(.van-picker__confirm) {
  color: var(--accent-primary);
}

.month-picker-popup :deep(.van-picker__cancel) {
  color: var(--text-muted);
}

.month-picker-popup :deep(.van-picker-column__item) {
  color: var(--text-secondary);
}

.month-picker-popup :deep(.van-picker-column__item--selected) {
  color: var(--text-primary);
}

/* 休息记录编辑弹窗 */
.rest-edit-popup {
  background: var(--card-bg) !important;
  max-height: 80vh;
}

.rest-edit-content {
  padding: 20px;
}

.rest-edit-content h3 {
  text-align: center;
  color: var(--text-primary);
  margin-bottom: 20px;
}

.edit-form {
  background: transparent !important;
  margin-bottom: 20px;
}

.edit-form :deep(.van-cell) {
  background: var(--card-bg-hover) !important;
  margin-bottom: 8px;
  border-radius: 8px;
}

.edit-form :deep(.van-cell__title) {
  color: var(--text-secondary);
}

.edit-form :deep(.van-cell__value) {
  color: var(--text-primary);
}

.edit-actions {
  padding-top: 10px;
}

/* 日期选择器弹窗 */
.date-picker-popup {
  background: var(--card-bg) !important;
}

.date-picker-popup :deep(.van-picker) {
  background: var(--card-bg) !important;
}

.date-picker-popup :deep(.van-picker__toolbar) {
  background: var(--card-bg);
}

.date-picker-popup :deep(.van-picker__title) {
  color: var(--text-primary);
}

.date-picker-popup :deep(.van-picker__confirm) {
  color: var(--accent-primary);
}

.date-picker-popup :deep(.van-picker__cancel) {
  color: var(--text-muted);
}

.date-picker-popup :deep(.van-picker-column__item) {
  color: var(--text-secondary);
}

.date-picker-popup :deep(.van-picker-column__item--selected) {
  color: var(--text-primary);
}

/* 确认对话框 */
.dialog-content {
  padding: 20px;
  text-align: center;
  color: var(--text-secondary);
}

.dialog-content strong {
  color: var(--accent-primary);
}
</style>

